#include "ui.h"
#include "config.h"

static void slider_event_func(lv_event_t* evnet);
static void update_value_label(lv_obj_t* label, uint8_t value);

void ui_init(ui_t* ui)
{
    ui->func = NULL;
    lv_obj_t* root = lv_obj_create(NULL);
    ui->root = root;
    lv_color_t bg_color = lv_color_make(242, 160, 158);
    lv_scr_load(root);
    lv_obj_set_style_bg_color(root, bg_color, 0);

    ui->label = lv_label_create(root);
    lv_obj_t* slider = lv_slider_create(root);
    ui->slider = slider;

    static lv_style_t slider_style;
    lv_style_init(&slider_style);
    lv_style_set_radius(&slider_style, 12);

    static lv_style_t slider_style2;
    lv_style_init(&slider_style2);
    lv_style_set_opa(&slider_style2, LV_OPA_0);

    static lv_style_t slider_style3;
    lv_style_init(&slider_style3);
    lv_style_set_radius(&slider_style3, 0);
    lv_style_set_bg_color(&slider_style3, lv_color_hex(0xffffff));

    lv_obj_add_style(slider, &slider_style2, LV_PART_KNOB);
    lv_obj_add_style(slider, &slider_style, LV_PART_MAIN);
    lv_obj_add_style(slider, &slider_style3, LV_PART_INDICATOR);

    lv_obj_align_to(ui->label, root, LV_ALIGN_CENTER, 50, 0);

    lv_obj_set_style_text_color(ui->label, lv_color_make(0xff, 0xff, 0xff), 0);
    lv_obj_refresh_ext_draw_size(ui->slider);

    lv_obj_center(slider);
    lv_obj_set_size(slider, 40, 120);
    lv_slider_set_range(slider, 0, 100);

    uint8_t defValue = 1;
    lv_obj_add_event_cb(slider, slider_event_func, LV_EVENT_VALUE_CHANGED, ui);
    lv_slider_set_value(slider, defValue, LV_ANIM_OFF);
    update_value_label(ui->label, defValue);
}
static void update_value_label(lv_obj_t* label, uint8_t value)
{
    char msg[10];
    sprintf(msg, "value: %d\n", value);
    lv_label_set_text((lv_label_t*)label, msg);
}
static void slider_event_func(lv_event_t* evnet)
{
    lv_event_code_t code = lv_event_get_code(evnet);
    if (code == LV_EVENT_VALUE_CHANGED)
    {
        lv_obj_t* slider = lv_event_get_target(evnet);
        uint32_t value = lv_slider_get_value(slider);
        ui_t* ui = (ui_t*)lv_event_get_user_data(evnet);
        update_value_label(ui->label, value);
        if (ui->func)
        {
            ui->func(value);
        }
    }

}

void ui_value_register_func(ui_t* ui, value_func f)
{
    ui->func = f;
}


uint8_t ui_get_value(ui_t* ui)
{
    return lv_slider_get_value(ui->slider);
}

void ui_set_value(ui_t* ui, uint8_t new_value)
{
    lv_slider_set_value(ui->slider, new_value, LV_ANIM_OFF);
}